using System.Net.Http;
using System.Collections;
using System.Resources;
using System.Security.Cryptography;
using System;
using UMC.Web;
using UMC.Data;
using System.Linq;
using UMC.Web.UI;
using System.Collections.Generic;
using UMC.Net;

namespace UMC.Proxy.Activities
{

    [Mapping("Proxy", "Market", Desc = "我的出售", Auth = WebAuthType.Admin)]
    class SiteMarketActivity : UMC.Web.WebActivity
    {
        public override void ProcessActivity(UMC.Web.WebRequest request, UMC.Web.WebResponse response)
        {
            var secret = UMC.Data.WebResource.Instance().Provider["appSecret"];
            if (String.IsNullOrEmpty(secret))
            {
                this.Prompt("当前版本未登记注册", false);
                this.Context.Response.Redirect("System", "License");
            }

            var root = this.AsyncDialog("Root", "oa");
            var webr = UMC.Proxy.Utility.Sign(new Uri(APIProxy.Uri, "Transfer").WebRequest(), secret).Put(new WebMeta().Put("type", "AppGoods").Put("root", root));
            var str = webr.ReadAsString();
            var appGood = JSON.Deserialize<WebMeta>(str);



            var Model = this.AsyncDialog("Model", gKey =>
            {

                var webr = UMC.Web.WebResource.Instance();


                UITitle uITItle = UITitle.Create();
                uITItle.Title = "发布市场";
                var sestion = UISection.Create(uITItle);

                var imageTextView = new UMC.Web.UI.UIImageTextValue(appGood["IconSrc"], "", "图标");
                imageTextView.Style.Name("image-width", "100");
                imageTextView.Click(new UIClick(request, gKey, "IconSrc"));
                // imageTextView.Tag("推荐");
                sestion.Add(imageTextView);
                // imageTextView.t

                sestion.AddCell("发布编码", $"{appGood["Key"]}_{root}");
                sestion.AddCell("发布名称", appGood["Caption"], new UIClick(request, gKey, "Caption"));


                var sT = appGood["Description"] ?? appGood["Caption"];
                if (sT.Length > 48)
                {
                    sT = sT.Substring(0, 48) + "...";
                }
                var desc = new UIDesc(sT);
                desc.Style.Height(40).Color(0x999).Size(13);
                desc.Click(new UIClick(request, gKey, "Description"));
                sestion.Add(desc);
                var Tel = appGood["Tel"];
                sestion.NewSection().AddCell("出售价格", $"{appGood["Price"]}元"
                 , new UIClick(request, gKey, "Price")).AddCell("售后电话", String.IsNullOrEmpty(Tel) ? "未设置" : Tel, new UIClick(request, gKey, "Tel"));


                switch (Utility.IntParse(appGood["Type"], 0))
                {
                    case 0:
                        sestion.NewSection().AddCell("发布方式", "反向代理", new UIClick(request, gKey, "Type"))
                        .AddCell("营销网址", appGood["HelpUrl"] ?? "未设置", new UIClick(request, gKey, "HelpUrl"));
                        break;
                    case 1:
                        sestion.NewSection().AddCell("发布方式", "身份互联", new UIClick(request, gKey, "Type"))
                        .AddCell("营销网址", appGood["HelpUrl"] ?? "未设置", new UIClick(request, gKey, "HelpUrl"));
                        break;
                    case 2:
                        var Domain = appGood["Domain"];
                        sestion.NewSection().AddCell("发布方式", "Saas互联", new UIClick(request, gKey, "Type"))
                        .AddCell("Saas网址", String.IsNullOrEmpty(Domain) ? "未设置" : Domain, new UIClick(request, gKey, "Domain"))
                        .AddCell("营销网址", appGood["HelpUrl"] ?? "未设置", new UIClick(request, gKey, "HelpUrl"));
                        break;
                }
                sestion.NewSection().AddCell("支持系统", appGood["OperatingSystem"]
                , new UIClick(request, gKey, "OperatingSystem")).AddCell("硬件配置", appGood["Hardware"], new UIClick(request, gKey, "Hardware"))
                .AddCell("演示网址", appGood["DemoUrl"] ?? "未设置", new UIClick(request, gKey, "DemoUrl"));



                var ness = sestion
                  .NewSection().AddCell("出售状态", appGood["State"]);

                ness.AddCell("应用类别", appGood["Category"] ?? "未设置", new UIClick(request, gKey, "Category"));

                if (appGood.ContainsKey("Hot"))
                {
                    ness.AddCell("热卖推荐", "是");
                }


                var ls = sestion.NewSection();
                var cell = UICell.UI("介绍说明", "", new UIClick(request, gKey, "Content"));
                cell.Style.BorderAll();
                ls.Add(cell);

                var Content = appGood["Content"];

                if (String.IsNullOrEmpty(Content) == false)
                {
                    ls.DisableSeparatorLine();
                    ls.AddCells(Markdown.Transform(Content));
                }
                else
                {
                    ls.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未有介绍").Put("icon", "\uF016"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                   new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                }
                sestion.UIFootBar = new UIFootBar() { IsFixed = true };
                sestion.UIFootBar.AddText(new UIEventText(appGood["Status"] == "1" ? "应用下架" : "应用上架").Click(new UIClick(request, gKey, "Status")),
                 new UIEventText("更新配置").Click(new UIClick(request, gKey, "PUT")).Style(new UIStyle().BgColor()));

                sestion.SendTo($"{request.Model}.{request.Command}.Del", this.Context, $"{request.Model}.{request.Command}", "System.Picture");

            });
            String Value = "";

            switch (Model)
            {
                case "IconSrc":
                    var media_id = this.AsyncDialog("IconSrc", g =>
                    {
                        if (request.IsApp)
                        {
                            return Web.UIDialog.CreateDialog("File");
                        }
                        else
                        {
                            var from = new Web.UIFormDialog() { Title = "图片上传" };

                            from.AddFile("选择图片", "IconSrc", String.Empty);

                            from.Submit("确认上传", $"{request.Model}.{request.Command}");
                            return from;
                        }
                    });
                    var iconsrc = new Uri(request.Url, media_id);

                    var postUrl = new Uri(APIProxy.Uri, "/TEMP" + iconsrc.AbsolutePath);

                    postUrl.WebRequest().Put(new System.Net.Http.StreamContent(new HttpClient().GetAsync(iconsrc).Result.Content.ReadAsStream()));
                    Value = postUrl.AbsoluteUri;
                    break;
                case "Category":
                    {

                        Value = Web.UIDialog.AsyncDialog(this.Context, "Category", g =>
                         {
                             var AppCategory = JSON.Deserialize<Hashtable>(UMC.Proxy.Utility.Sign(new Uri(APIProxy.Uri, "Transfer").WebRequest(), secret).Put(new WebMeta().Put("type", "AppGoods")).ReadAsString())["Category"] as Array;

                             var dl = new UISheetDialog() { Title = "应用分类" };
                             dl.Cells(3);// = 3;
                             for (var i = 0; i < AppCategory.Length; i++)
                             {
                                 dl.Put(AppCategory.GetValue(i) as string, i.ToString());
                             }
                             return dl;
                         });

                    }
                    break;
                case "Caption":
                    Value = Web.UIDialog.AsyncDialog(this.Context, "Caption", g =>
                    {
                        var dl = new Web.UIFormDialog() { Title = "应用标题" };
                        dl.AddText("应用标题", "Caption", appGood["Caption"]);
                        dl.Submit("确认更改", $"{request.Model}.{request.Command}");
                        return dl;
                    });

                    break;
                case "Description":
                    Value = Web.UIDialog.AsyncDialog(this.Context, "Description", g =>
                      {
                          var dl = new Web.UIFormDialog() { Title = "应用简介" };
                          dl.AddTextarea("简介", "Description", appGood["Description"]).Put("Rows", 10);
                          dl.Submit("确认更改", $"{request.Model}.{request.Command}");
                          return dl;
                      });

                    break;

                case "Price":
                    Value = this.AsyncDialog("Price", g => new Web.UINumberDialog(appGood["Price"]) { Title = "出售价格" });


                    break;

                case "Type":
                    Value = this.AsyncDialog("Type", g =>
                   {
                       return new Web.UISheetDialog() { Title = "发布方式" }.Put("反向代理", "0").Put("身份互联", "1")
                       .Put("Saas互联", "2");

                   });
                    break;
                case "HelpUrl":
                    var HelpUrl = this.AsyncDialog("HelpUrl", g =>
                    {
                        return new Web.UITextDialog(appGood["HelpUrl"]) { Title = "营销网址" };
                    });
                    try
                    {
                        Value = new Uri(HelpUrl).AbsoluteUri;
                    }
                    catch
                    {
                        this.Prompt("网址格式不正确");
                    }
                    break;

                case "Domain":
                    var Domain = this.AsyncDialog("Domain", g =>
                    {
                        return new Web.UITextDialog(appGood["Domain"]) { Title = "Saas网址" };
                    });
                    try
                    {
                        Value = new Uri(new Uri(Domain), "/").AbsoluteUri;

                    }
                    catch
                    {
                        this.Prompt("网址格式不正确");
                    }
                    break;
                case "Tel":
                    Value = this.AsyncDialog("Tel", g =>
                        {
                            return new Web.UITextDialog(appGood["Tel"]) { Title = "售后电话" };
                        });
                    break;
                case "Status":
                    Value = "Change";
                    break;
                case "OperatingSystem":
                    var OperatingSystem = appGood["OperatingSystem"];
                    // var l=
                    Value = this.AsyncDialog("OperatingSystem", g =>
                    {
                        var check = new Web.UICheckboxDialog() { Title = "支持系统" };
                        check.Options.Put("Linux", "Linux", OperatingSystem?.Contains("Linux") == true)
                        .Put("Winfows", "Winfows", OperatingSystem?.Contains("Winfows") == true)
                        .Put("MacOS", "MacOS", OperatingSystem?.Contains("MacOS") == true);
                        return check;
                    });
                    break;
                case "Hardware":

                    Value = this.AsyncDialog("Hardware", g =>
                      {
                          var check = new Web.UISheetDialog() { Title = "硬件配置" };
                          check.Put("2核4G").Put("4核8G").Put("4核16G").Put("8核32G");
                          return check;
                      });

                    break;
                case "DemoUrl":

                    var DemoUrl = this.AsyncDialog("DemoUrl", g =>
                    {
                        return new Web.UITextDialog(appGood["DemoUrl"]) { Title = "演示网址" };
                    });
                    try
                    {
                        Value = new Uri(new Uri(DemoUrl), "/").AbsoluteUri;

                    }
                    catch
                    {
                        this.Prompt("网址格式不正确");

                    }
                    break;
                case "PUT":
                    var site = DataFactory.Instance().Site(root);
                    if (site == null)
                    {
                        this.Prompt("当前应用配置不存在，不可更新配置");
                    }
                    var data = SiteActivity.PutMarket(site, secret);

                    this.Prompt(data?["msg"] ?? "提交异常");

                    break;
                case "Content":
                    {
                        Value = Web.UIDialog.AsyncDialog(this.Context, "Content", r =>
                        {

                            var from5 = new UIFormDialog() { Title = "介绍说明" };
                            from5.AddTextarea("应用介绍，支持MD格式", "Content", appGood["Content"]).Put("Rows", 20).NotRequired();
                            from5.Submit("确认更改", $"{request.Model}.{request.Command}");
                            return from5;
                        });


                    }
                    break;
            }
            if (String.IsNullOrEmpty(Value) == false)
            {
                var AppCategory = JSON.Deserialize<WebMeta>(UMC.Proxy.Utility.Sign(new Uri(APIProxy.Uri, "Transfer").WebRequest(), secret)
                .Put(new WebMeta().Put("type", "AppGoods", "root", root, "key", Model, "value", Value)).ReadAsString());
                if (AppCategory.ContainsKey("msg"))
                {
                    this.Prompt("提示", AppCategory["msg"]);
                }

            }
            this.Context.Send(true);






        }
    }
}